package com.example.allplan.Fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBarDrawerToggle;
import androidx.appcompat.widget.Toolbar;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.allplan.Activity.BianJiJiHuaActivity;
import com.example.allplan.Activity.BianJiYiGeJiHuaBao;
import com.example.allplan.Activity.GuanLiJiHuaBaoActivity;
import com.example.allplan.Activity.JiHuaYeMianActivity;
import com.example.allplan.ItemTouchHelper.JiHuaBaoTouchCallback;
import com.example.allplan.JavaBean.JiHuaBaoJavaBean;
import com.example.allplan.JavaBean.JiHuaJavaBean;
import com.example.allplan.MyApplication;
import com.example.allplan.MyView.MyDrawerLayout;
import com.example.allplan.R;
import com.example.allplan.RecyclerAdapter.JiHuaBaoRecyclerAdapter;
import com.example.allplan.RecyclerAdapter.JiHuaXianShiAdapter;
import com.example.allplan.StaticFangfa.BiaoQingZhuanHuan;
import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;

public class JiHuaFragment extends BaseFragment implements View.OnClickListener {
    RecyclerView mJi_hua_bao_recyclerview, mji_hua_lie_biao_recyclerview;
    ArrayList<JiHuaBaoJavaBean> mList;
    ArrayList<JiHuaJavaBean> msuoyoujihualist, mxianshidelist;
    JiHuaBaoJavaBean now_xuan_zhong;
    JiHuaBaoRecyclerAdapter mJi_hua_bao_recyclerview_adapter;
    JiHuaXianShiAdapter mjihuaxianshiadapter;
    JiHuaBaoTouchCallback mcall;
    ImageView wushujutu;
    View mview;
    boolean jiazaiguo = false;
    MyApplication myapp;
    TextView biao_ti_biao_qing_textview, biao_ti_bao_ming_textview;
    Boolean is_di_yi_ci_jia_zai;
    MyDrawerLayout ce_hua_lan_drawerlayout;
    Toolbar ji_hua_toolbar;
    LinearLayout tian_jia_ji_hua_bao, guan_li_ji_hua_bao;
    FloatingActionButton tian_jia_ji_hua;
    final int TIAN_JIA_HUO_GENG_XIN_JI_HUA_BAO_CODE = 11, TIAN_JIA_HUO_GENG_XIN_JI_HUA_BAO_RESULT_CODE = 12;

    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        is_di_yi_ci_jia_zai = true;
        mview = inflater.inflate(R.layout.ji_hua_fragment_layout, container, false);
        init();
        return mview;
    }

    void init() {
        myapp = MyApplication.getInstance();
        wushujutu = mview.findViewById(R.id.wu_shu_ju_xian_shi_de_tu_imageView);
        mji_hua_lie_biao_recyclerview = mview.findViewById(R.id.ji_hua_lie_biao_recyclerView);
        tian_jia_ji_hua = mview.findViewById(R.id.tian_jia_ji_hua_floatbutton);
        tian_jia_ji_hua.setOnClickListener(this);
        mJi_hua_bao_recyclerview = mview.findViewById(R.id.ce_hua_lan_ji_hua_bao_recycleView);
        biao_ti_biao_qing_textview = mview.findViewById(R.id.biao_ti_lan_xian_shi_biao_qing_TextView);
        biao_ti_bao_ming_textview = mview.findViewById(R.id.biao_ti_lan_xian_shi_bao_ming_TextView);
        ce_hua_lan_drawerlayout = mview.findViewById(R.id.ce_hua_lan_drawerlayout);
        ji_hua_toolbar = mview.findViewById(R.id.ji_hua_toolbar);
        tian_jia_ji_hua_bao = mview.findViewById(R.id.tian_jia_ji_hua_bao);
        tian_jia_ji_hua_bao.setOnClickListener(this);
        guan_li_ji_hua_bao = mview.findViewById(R.id.guan_li_ji_hua_bao);
        guan_li_ji_hua_bao.setOnClickListener(this);
//        ji_hua_toolbar.setNavigationOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                ce_hua_lan_drawerlayout.openDrawer(Gravity.LEFT);
//            }
//        });
       /* if(is_di_yi_ci_jia_zai){
            biao_ti_biao_qing_textview.setText(BiaoQingZhuanHuan.biao_qing_int_to_string(127968));
            biao_ti_bao_ming_textview.setText("默认分组");
            is_di_yi_ci_jia_zai=false;
        }*/

        ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(requireActivity(), ce_hua_lan_drawerlayout, ji_hua_toolbar, R.string.open, R.string.close);
        actionBarDrawerToggle.syncState();
        ce_hua_lan_drawerlayout.addDrawerListener(actionBarDrawerToggle);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

    }

    void reload() {
        lazyLoadData();
    }

    @Override
    protected void lazyLoadData() {
        mxianshidelist = new ArrayList<JiHuaJavaBean>();
        mList = myapp.mSuoYouJiHuaBaoSQCaoZuo.reloadAllJiHuaBao();
        Collections.sort(mList);
        now_xuan_zhong = mList.get(0);
        mJi_hua_bao_recyclerview_adapter = new JiHuaBaoRecyclerAdapter(mList, new JiHuaBaoRecyclerAdapter.onItemClickListener() {

            @SuppressLint("RestrictedApi")
            public void onClick(int pos, Context mcon) {
                tian_jia_ji_hua.setVisibility(View.VISIBLE);
                biao_ti_biao_qing_textview.setText(BiaoQingZhuanHuan.biao_qing_int_to_string(mList.get(pos).getBiao_qing_fu_hao_zhi()));
                biao_ti_bao_ming_textview.setText(mList.get(pos).getBao_ming());
                ce_hua_lan_drawerlayout.closeDrawer(Gravity.LEFT);
                if (pos == mList.size() - 1) {
                    tian_jia_ji_hua.setVisibility(View.GONE);
                }
                now_xuan_zhong = mList.get(pos);
                jiazaixianshi();
            }
        }, getActivity());
        mJi_hua_bao_recyclerview.setAdapter(mJi_hua_bao_recyclerview_adapter);
        mJi_hua_bao_recyclerview.setLayoutManager(new LinearLayoutManager(getActivity()));

        biao_ti_biao_qing_textview.setText(BiaoQingZhuanHuan.biao_qing_int_to_string(127968));
        biao_ti_bao_ming_textview.setText("默认分组");
        jiazaisuoyoujihua();
        jiazaixianshi();
    }

    void jiazaisuoyoujihua() {
        msuoyoujihualist = myapp.mSuoYouJiHuaSQCaoZuo.reloadAllJiHua();

    }

    JiHuaBaoJavaBean genjuidzhaobean(int n) {
        for (int i = 0; i < mList.size(); i++) {
            if (mList.get(i).getId() == n) {
                return mList.get(i);
            }
        }
        return null;
    }

    int genjuidzhaoint(int n) {
        for (int i = 0; i < mList.size(); i++) {
            if (mList.get(i).getId() == n) {
                return i;
            }
        }
        return -1;
    }

    void gengxinsuoyouliebiao(JiHuaJavaBean o) {
        for (int i = 0; i < msuoyoujihualist.size(); i++) {
            if (o.getId() == msuoyoujihualist.get(i).getId()) {
                msuoyoujihualist.set(i, o);
                break;
            }
        }
    }

    void shanchusuoyouliebiaozhongyige(JiHuaJavaBean o) {
        for (int i = 0; i < msuoyoujihualist.size(); i++) {
            if (o.getId() == msuoyoujihualist.get(i).getId()) {
                msuoyoujihualist.remove(i);
                return;
            }
        }
    }

    boolean jianchabaocunzai(int n) {
        for (int i = 0; i < mList.size() - 1; i++) {
            if (n == mList.get(i).getId()) return true;
        }
        return false;
    }

    void jiazaixianshi() {

        if (mxianshidelist.size() > 0)
            mxianshidelist.clear();
        for (int i = 0; i < msuoyoujihualist.size(); i++) {
            if (msuoyoujihualist.get(i).getSuo_shu_ji_hua_bao_id() == now_xuan_zhong.getId()) {
                mxianshidelist.add(msuoyoujihualist.get(i));
                //Log.d("1422",msuoyoujihualist.get(i).getSuo_shu_ji_hua_bao_id()+"");
            }
        }
        Collections.sort(mxianshidelist);
        mjihuaxianshiadapter = new JiHuaXianShiAdapter(mxianshidelist, new JiHuaXianShiAdapter.onItemClickListener() {
            @Override
            public void onClick(int pos, Context mcon) {
                if (mxianshidelist.get(pos).getSuo_shu_ji_hua_bao_id() != 1) {
                    Log.d("1422", mxianshidelist.get(pos).getSuo_shu_ji_hua_bao_id() + "");
                    Intent intent = new Intent(mcon, JiHuaYeMianActivity.class);
                    intent.putExtra("biao_ti", mxianshidelist.get(pos).getMing_cheng());
                    intent.putExtra("wen_jian_ming", mxianshidelist.get(pos).getWen_jian_ming());
                    startActivityForResult(intent, 41);
                } else {
                    if (jianchabaocunzai(mxianshidelist.get(pos).getYuan_suo_shu_id())) {
                        mxianshidelist.get(pos).setSuo_shu_ji_hua_bao_id(mxianshidelist.get(pos).getYuan_suo_shu_id());
                        mxianshidelist.get(pos).setPai_xu_you_biao(genjuidzhaobean(mxianshidelist.get(pos).getSuo_shu_ji_hua_bao_id()).getJi_hua_shu());
                        mList.get(genjuidzhaoint(mxianshidelist.get(pos).getSuo_shu_ji_hua_bao_id())).setJi_hua_shu(mList.get(genjuidzhaoint(mxianshidelist.get(pos).getSuo_shu_ji_hua_bao_id())).getJi_hua_shu() + 1);
                        mList.get(mList.size() - 1).setJi_hua_shu(mList.get(mList.size() - 1).getJi_hua_shu() - 1);
                    }else {
                        mxianshidelist.get(pos).setSuo_shu_ji_hua_bao_id(0);
                        mxianshidelist.get(pos).setYuan_suo_shu_id(0);
                        mxianshidelist.get(pos).setPai_xu_you_biao(genjuidzhaobean(mxianshidelist.get(pos).getSuo_shu_ji_hua_bao_id()).getJi_hua_shu());
                        mList.get(genjuidzhaoint(mxianshidelist.get(pos).getSuo_shu_ji_hua_bao_id())).setJi_hua_shu(mList.get(genjuidzhaoint(mxianshidelist.get(pos).getSuo_shu_ji_hua_bao_id())).getJi_hua_shu() + 1);
                        mList.get(mList.size() - 1).setJi_hua_shu(mList.get(mList.size() - 1).getJi_hua_shu() - 1);
                    }
                    gengxinsuoyouliebiao(mxianshidelist.get(pos));
                    myapp.mSuoYouJiHuaSQCaoZuo.update_one(mxianshidelist.get(pos));
                    myapp.mSuoYouJiHuaBaoSQCaoZuo.update_one(mList.get(genjuidzhaoint(mxianshidelist.get(pos).getSuo_shu_ji_hua_bao_id())));
                    myapp.mSuoYouJiHuaBaoSQCaoZuo.update_one(mList.get(mList.size() - 1));
                    mxianshidelist.remove(pos);
                    // Log.d("kaishi",System.currentTimeMillis()+"");
                    for (int i = pos; i < mxianshidelist.size(); i++) {
                        mxianshidelist.get(i).setPai_xu_you_biao(mxianshidelist.get(i).getPai_xu_you_biao() - 1);
                        myapp.mSuoYouJiHuaSQCaoZuo.update_one(mxianshidelist.get(i));
                    }
                    mjihuaxianshiadapter.notifyItemRemoved(pos);
                    //Log.d("kaishi1",System.currentTimeMillis()+"");
                    ce_hua_lan_drawerlayout.setCantclick(true);
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                Thread.sleep(450);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {

                                    //madapter.notifyDataSetChanged();
                                    ce_hua_lan_drawerlayout.setCantclick(false);
                                    //Log.d("kaishi2",System.currentTimeMillis()+"");
                                }
                            });
                        }
                    }).start();
                }

            }
        }, getActivity());
        mji_hua_lie_biao_recyclerview.setAdapter(mjihuaxianshiadapter);
        mji_hua_lie_biao_recyclerview.setLayoutManager(new LinearLayoutManager(getActivity()));
        if (!jiazaiguo) {
            mcall = new JiHuaBaoTouchCallback(new JiHuaBaoTouchCallback.itemtouchhelpercallback() {
                @Override
                public void onitemmove(int frompos, int topos) {
                    int temp = mxianshidelist.get(frompos).getPai_xu_you_biao();
                    mxianshidelist.get(frompos).setPai_xu_you_biao(mxianshidelist.get(topos).getPai_xu_you_biao());
                    mxianshidelist.get(topos).setPai_xu_you_biao(temp);
                    Collections.swap(mxianshidelist, frompos, topos);
                    gengxinsuoyouliebiao(mxianshidelist.get(frompos));
                    gengxinsuoyouliebiao(mxianshidelist.get(topos));
                    mjihuaxianshiadapter.notifyItemMoved(frompos, topos);
                    myapp.mSuoYouJiHuaSQCaoZuo.update_one(mxianshidelist.get(frompos));
                    myapp.mSuoYouJiHuaSQCaoZuo.update_one(mxianshidelist.get(topos));
                }

                @Override
                public void onitemswipe(int direction) {
                    if (mxianshidelist.get(direction).getSuo_shu_ji_hua_bao_id() != 1) {
                        Log.d("14223", mxianshidelist.get(direction).getSuo_shu_ji_hua_bao_id() + "");
                        mxianshidelist.get(direction).setYuan_suo_shu_id(mxianshidelist.get(direction).getSuo_shu_ji_hua_bao_id());
                        mxianshidelist.get(direction).setSuo_shu_ji_hua_bao_id(1);
                        mxianshidelist.get(direction).setPai_xu_you_biao(mList.get(mList.size() - 1).getJi_hua_shu());
                        mList.get(mList.size() - 1).setJi_hua_shu(mList.get(mList.size() - 1).getJi_hua_shu() + 1);
                        now_xuan_zhong.setJi_hua_shu(now_xuan_zhong.getJi_hua_shu() - 1);
                        gengxinsuoyouliebiao(mxianshidelist.get(direction));
                        myapp.mSuoYouJiHuaSQCaoZuo.update_one(mxianshidelist.get(direction));
                        myapp.mSuoYouJiHuaBaoSQCaoZuo.update_one(now_xuan_zhong);
                        myapp.mSuoYouJiHuaBaoSQCaoZuo.update_one(mList.get(mList.size() - 1));
                        mxianshidelist.remove(direction);
                        // Log.d("kaishi",System.currentTimeMillis()+"");
                        for (int i = direction; i < mxianshidelist.size(); i++) {
                            mxianshidelist.get(i).setPai_xu_you_biao(mxianshidelist.get(i).getPai_xu_you_biao() - 1);
                            myapp.mSuoYouJiHuaSQCaoZuo.update_one(mxianshidelist.get(i));
                        }
                        mjihuaxianshiadapter.notifyItemRemoved(direction);
                        //Log.d("kaishi1",System.currentTimeMillis()+"");
                        ce_hua_lan_drawerlayout.setCantclick(true);
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    Thread.sleep(450);
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                                getActivity().runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {

                                        //madapter.notifyDataSetChanged();
                                        ce_hua_lan_drawerlayout.setCantclick(false);
                                        //Log.d("kaishi2",System.currentTimeMillis()+"");
                                    }
                                });
                            }
                        }).start();
                    } else {

                        mList.get(mList.size() - 1).setJi_hua_shu(mList.get(mList.size() - 1).getJi_hua_shu() - 1);
                        shanchusuoyouliebiaozhongyige(mxianshidelist.get(direction));

                        myapp.mSuoYouJiHuaBaoSQCaoZuo.update_one(mList.get(mList.size() - 1));
                        myapp.mSuoYouJiHuaSQCaoZuo.deleteone(mxianshidelist.get(direction));
                        getActivity().deleteDatabase(mxianshidelist.get(direction).getWen_jian_ming());
                        myapp.putSH_Int(myapp.JI_HUA_TIAO_SHU_SHARE_NAME, --myapp.ji_hua_tiao_shu);
                        mxianshidelist.remove(direction);
                        for (int i = direction; i < mxianshidelist.size(); i++) {
                            mxianshidelist.get(i).setPai_xu_you_biao(mxianshidelist.get(i).getPai_xu_you_biao() - 1);
                            myapp.mSuoYouJiHuaSQCaoZuo.update_one(mxianshidelist.get(i));
                        }
                        mjihuaxianshiadapter.notifyItemRemoved(direction);
                        //Log.d("kaishi1",System.currentTimeMillis()+"");
                        ce_hua_lan_drawerlayout.setCantclick(true);
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    Thread.sleep(450);
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                                getActivity().runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {

                                        //madapter.notifyDataSetChanged();
                                        ce_hua_lan_drawerlayout.setCantclick(false);
                                        //Log.d("kaishi2",System.currentTimeMillis()+"");
                                    }
                                });
                            }
                        }).start();

                    }

                }
            });
            ItemTouchHelper mhelper = new ItemTouchHelper(mcall);
            mhelper.attachToRecyclerView(mji_hua_lie_biao_recyclerview);
            jiazaiguo = true;
        }


        if (mxianshidelist.size() > 0) {
            wushujutu.setVisibility(View.GONE);
        } else {
            wushujutu.setVisibility(View.VISIBLE);
        }
    }
    void yidonghoushezhipaixu(int id){
        int pos=-1;
        for(int i=0;i<mxianshidelist.size();i++){
            if(id==mxianshidelist.get(i).getId()){
                pos=i;
                break;
            }
        }
        mxianshidelist.remove(pos);
        for (int i = pos; i < mxianshidelist.size(); i++) {
            mxianshidelist.get(i).setPai_xu_you_biao(mxianshidelist.get(i).getPai_xu_you_biao() - 1);
            myapp.mSuoYouJiHuaSQCaoZuo.update_one(mxianshidelist.get(i));
        }
        mjihuaxianshiadapter.notifyItemRemoved(pos);
        //Log.d("kaishi1",System.currentTimeMillis()+"");
        ce_hua_lan_drawerlayout.setCantclick(true);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(450);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                        //madapter.notifyDataSetChanged();
                        ce_hua_lan_drawerlayout.setCantclick(false);
                        //Log.d("kaishi2",System.currentTimeMillis()+"");
                    }
                });
            }
        }).start();

    }

    @Override
    public void onClick(View v) {
        Intent mIntent;
        switch (v.getId()) {
            case R.id.tian_jia_ji_hua_bao:
                mIntent = new Intent(getActivity(), BianJiYiGeJiHuaBao.class);
                startActivityForResult(mIntent, TIAN_JIA_HUO_GENG_XIN_JI_HUA_BAO_CODE);
                break;
            case R.id.guan_li_ji_hua_bao:
                mIntent = new Intent(getActivity(), GuanLiJiHuaBaoActivity.class);
                startActivityForResult(mIntent, 21);
                break;
            case R.id.tian_jia_ji_hua_floatbutton:
                mIntent = new Intent(getActivity(), BianJiJiHuaActivity.class);
                mIntent.putExtra("suo_shu_id", now_xuan_zhong.getId());
                mIntent.putExtra("bao_han_ren_wu_shu", now_xuan_zhong.getJi_hua_shu());
                startActivityForResult(mIntent, 31);
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == TIAN_JIA_HUO_GENG_XIN_JI_HUA_BAO_CODE && resultCode == TIAN_JIA_HUO_GENG_XIN_JI_HUA_BAO_RESULT_CODE) {
            reload();
        } else if (requestCode == 21 && resultCode == 22) {
            reload();
        } else if (requestCode == 31 && resultCode == 32) {
            now_xuan_zhong.setJi_hua_shu(now_xuan_zhong.getJi_hua_shu() + 1);
            myapp.mSuoYouJiHuaBaoSQCaoZuo.update_one(now_xuan_zhong);
            jiazaisuoyoujihua();
            jiazaixianshi();
        } else if (requestCode == 41 && resultCode == 42) {
            now_xuan_zhong.setJi_hua_shu(now_xuan_zhong.getJi_hua_shu() + 1);
            myapp.mSuoYouJiHuaBaoSQCaoZuo.update_one(now_xuan_zhong);
            jiazaisuoyoujihua();
            jiazaixianshi();
        } else if (requestCode == 41 && resultCode == 43) {
            int id=data.getIntExtra("ji_hua_id",-1);
            yidonghoushezhipaixu(id);
            reload();
        }
    }
}
